import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import { useGlobalStore } from "@/stores/modules/global";
const cancelTokenSources = new Map();
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: import.meta.env.VITE_API_URL,
  withCredentials: true, // send cookies when cross-domain requests
  // 超时
  timeout: 20 * 1000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "X-GateWay-sv": "9EF4D7CBD18549BC98BB4221B62AC4D1C4BAB43B",
    PLATFORM: "web",
    VERSION: "2.7.0"
  }
});

// request拦截器
service.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    const globalStore = useGlobalStore();
    // 是否需要token
    let needToken = config.headers.needToken || true;
    if (needToken) {
      config.headers["token"] = userStore.token;
      config.headers["userId"] = userStore.userInfo.userId;
    }
    config.headers["LANGUAGE"] = globalStore.language;
    config.headers["DEVICEID"] = "3968517";

    const source = axios.CancelToken.source();
    cancelTokenSources.set(source.token, source.cancel);
    config.cancelToken = source.token;
    return config;
  },
  error => {
    console.log(error);
    Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 二进制数据则直接返回
    if (res.request.responseType === "blob" || res.request.responseType === "arraybuffer") {
      return res.data;
    }
    if (res.config.url == "/user/common/heartbeat") {
      return res.data;
    }

    if (code === 200 || code == 2066 || code == 2016 || code == 2062 || code == 2043 || code == 2007) {
      // 正常
      return res.data;
    } else if (code === 401 || code == 2060) {
      // 登录状态已过期
      ElMessage({
        message: "登录状态已过期",
        type: "error"
      });
      // 取消所有待响应请求
      for (const [token, cancel] of cancelTokenSources) {
        cancel(token);
      }
      // 退出登录显示登陆弹窗
      userStore.logout();
      return res.data;
    } else {
      const resDes = (res.data.desc || res.data.msg || "").substring(0, 50);
      ElMessage({
        message: resDes,
        type: "warning"
      });
      return res.data;
    }
  },
  error => {
    console.log("onRejected err=" + error);
    return Promise.reject(error);
  }
);

export default service;
